<?php
class friends_model extends CI_Model {
	
	function get_commend_user(){
		$user_id=$this->session->userdata('user_id');
		$this->db->where('user_id !=',$user_id);
		$this->db->order_by('user_id','desc');
		$query=$this->db->get('user',1);
		return $query->row();	
	}
	
	function get_commend_user_setting($user_id){
		$this->db->where('user_id',$user_id);
		$query=$this->db->get('user_setting');
		return $query->row();
	}
	
	function is_friend($fuid){
		$user_id=$this->session->userdata('user_id');
		$this->db->where('user_id',$user_id);
		$this->db->where('fuid',$fuid);
		$this->db->where('status',1);
		$query=$this->db->get('friend');
		//如果是好友了
		if($query->num_rows()==1)
			return 'yes';
		
		$this->db->where('user_id',$user_id);
		$this->db->where('fuid',$fuid);
		$this->db->where('status',0);
		$query=$this->db->get('friend');
		// 若果是还没通过
		if($query->num_rows()==1)
			return 'wait';

		//如果不是的
		return 'no';
	}

	function add_friend($fuid){
		$this->db->where('user_id',$fuid);
		$query_friend=$this->db->get('user');
		$this->db->where('user_id',$this->session->userdata('user_id'));
		$query_user=$this->db->get('user');
		
		$friend_row=$query_friend->row();
		$user_row=$query_user->row();
		
		$data_user=array(
				'user_id'=>$user_row->user_id,
				'fuid'=>$friend_row->user_id,
				'fusername'=>$friend_row->user_name,
				'status'=>0
		);
		$query1=$this->db->insert('friend',$data_user);
		
		$data_friend=array(
				'user_id'=>$friend_row->user_id,
				'fuid'=>$user_row->user_id,
				'fusername'=>$user_row->user_name,
				'status'=>0
		);
		$query2=$this->db->insert('friend',$data_friend);
		
		return $query1 && $query2;
		
	}
	
	function concept($id){
		$this->db->where("user_id",$this->session->userdata('user_id'));
		$this->db->where('fuid',$id);
		$query_1=$this->db->update('friend',array("status"=>1));
		
		$this->db->where("user_id",$id);
		$this->db->where('fuid',$this->session->userdata('user_id'));
		$query_2=$this->db->update('friend',array("status"=>1));
		
		return $query_1 && $query_2;	
	}
	
	function refuse($id){
		$user_id=$this->session->userdata('user_id');
		//直接删除?
		$query_1=$this->db->delete('friend',array('user_id'=>$user_id,'fuid'=>$id));
		$query_2=$this->db->delete('friend',array('user_id'=>$id,'fuid'=>$user_id));
		
		return $query_1 && $query_2;
	}
	
	function get_friends()
	{
		$user_id=$this->session->userdata('user_id');
		$this->db->where('user_id =',$user_id);
		$this->db->order_by('fusername','asc');
		$query=$this->db->get('friend');
		return $query->result();	
	}
}
